<template>
  <div class="addLandPage">
    <div class="back" @click="back()"><i class="el-icon-back"></i>返回</div>
    <el-form
      :model="Form"
      :rules="rules"
      ref="mainForm"
      label-width="100px"
      class="addForm"
    >
      <el-form-item prop="mapData" class="addMapInForm" label="绘制地块">
        <el-button
          @click="dialogVisible = true"
          ref="mapData"
          class="openMapBtn"
          type="primary"
        >
          <i class="el-icon-edit-outline"></i>&nbsp; 绘制地块真实轮廓
        </el-button>
        <div class="text">
          绘制地块轮廓有助于管理知晓农产品来源于哪个真实地块
        </div>
      </el-form-item>
      <el-form-item prop="landName" label="地块名称">
        <el-input v-model="Form.landName" class="landName"></el-input>
      </el-form-item>
      <el-form-item prop="landType" label="地块类型">
        <el-select
          v-model="Form.landType"
          class="landName"
          placeholder="请选择"
        >
          <el-option
            v-for="item in landTypes"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="responsiblePerson" label="负责人">
        <el-select
          v-model="Form.responsiblePerson"
          class="landName"
          placeholder="请选择"
          @change="onSelectChange"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="Form.phone" class="landName"></el-input>
      </el-form-item>
      <el-form-item label="地块地址" prop="address">
        <el-input v-model="Form.address" class="landName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="submitBtn"
          @click="submitForm('dynamicValidateForm')"
          >完 成</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="80%" :boolean="true">
      <areaMap
        v-if="dialogVisible"
        @areaData="getAreaData"
        :landList="landList"
      ></areaMap>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="mapAddBtn()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import titBox from '@/components/titBox'
import areaMap from '@/views/mapAdd/components/map.vue'
import { AddlandData, getUserListApi, getMaplandApi } from '@/api/landAdd'
import { getSysSonDictListApi } from '@/api/dict'

export default {
  name: 'MeilinPCIndex',
  components: {
    // titBox,
    areaMap
  },
  data () {
    return {
      map: {},
      longitude: 120.524224,
      latitude: 30.184564,
      // showMap: false, //
      dialogVisible: false,
      // baseId 农场Id
      // landArea 地块面积
      // landCenter 地块中心点
      // landLatLng 圈地经纬度
      // landName 地块名称
      // landType 地块类型
      // landZoom 地块缩放值
      Form: {
        baseId: 1,
        landName: '',
        landType: '',
        phone: null,
        color: '#49cc90, #1f64c1'
      },
      rules: {
        // mapData: [
        //   { required: true, message: '请输入用户名', trigger: 'blur' },
        //   { validator: this.validateMapData, trigger: 'blur' }
        // ]，
        landName: [
          { required: true, message: '请输入地块名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        landType: [
          { required: true, message: '请选择地块类型', trigger: 'blur' }
        ],
        responsiblePerson: [
          { required: true, message: '请选择负责人', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请正确填写手机号码', trigger: 'blur' }
        ]
      },
      mapData: {}, // 合并到Form表单的数据
      userList: [], // 人员列表
      landTypes: [], // 地块类型
      baseId: 1
    }
  },

  mounted () {
    this.baseId = this.$store.getters.userInfo.baseId
    this.Form.baseId = this.$store.getters.userInfo.baseId
    this.getUserList(this.baseId)
    this.getMapland(this.baseId)
    this.getSysSonDictList()
  },

  methods: {
    // map组建子传父 传递圈地数据
    getAreaData (e) {
      console.log(e, '父getAreaData')
      if (
        Object.keys(this.mapData).length >= 0 &&
        Object.keys(e).length !== 1
      ) {
        this.mapData.geoInfo = JSON.stringify(e.currentLnglats)// 地块经纬度
        this.mapData.landArea = parseFloat((e.currentArea * 0.0015).toFixed(2))// 地块面积
        this.mapData.geoCenter = JSON.stringify(e.target.Eo)// 中心经纬度
        this.mapData.geoZoom = e.currentPolygon.KE.fW// 缩放度
        this.Form.address = e.landInfo
        this.$message.success('操作成功')
      }
      if (e.landInfo === null) {
        this.Form.address = e.landInfo
      }
    },
    // handleAddPoint () {
    //   const T = window.T
    //   console.log(T)
    //   this.map.clearOverLays() // 清空原来的标注点
    //   const point = new T.LngLat(
    //     (this.longitude -= 0.01),
    //     (this.latitude -= 0.01)
    //   )
    //   const marker = new T.Marker(point)
    //   this.map.addOverLay(marker) // 添加标注点
    //   // 点击标注点事件，添加信息窗口
    //   const markerInfoWin = new T.InfoWindow('信息窗口')
    //   marker.addEventListener('click', function () {
    //     marker.openInfoWindow(markerInfoWin)
    //   })
    // },
    // 表单提交
    async submitForm () {
      if (!this.validateMapFromData()) {
        this.$message.error('请绘制地块')
      } else {
        console.log('校验')
        this.Form.geoZoom = this.Form.geoZoom.toString()
        this.Form.phone = Number(this.Form.phone)
        const res = await AddlandData(this.Form)
        if (res.code === 200) {
          this.$message.success('添加地块成功')
          this.$router.push({
            path: '/shuzhongtian/agriLand',
            query: { ...this.$route.query }
          }) // 返回详情
        } else {
          this.$message.error('添加地块失败')
        }
      }
    },
    // 地图弹窗数据校验
    validateMapFromData () {
      console.log(this.mapData)
      if (Object.keys(this.mapData).length === 0) {
        console.log('数据为空')
        return false // 数据为空，校验失败
      }
      return true // 数据不为空，校验通过
    },
    // 弹窗确认
    mapAddBtn () {
      if (Object.keys(this.mapData).length > 0) {
        this.dialogVisible = false
        this.Form = Object.assign({}, this.Form, this.mapData)
      } else {
        this.$message.error('请绘制地块')
      }
    },
    // 弹窗取消
    closeDialog () {
      this.$message('绘制已取消')
      this.mapData = {}
      this.Form.address = null
      this.dialogVisible = false
    },

    // 返回
    back () {
      this.$router.push({
        name: 'dashboard'
      })
    },
    // 地块列表，添加时回显到地图上
    async getMapland (baseId) {
      const res = await getMaplandApi(baseId)
      console.log(res.data)
      this.landList = res.data
    },
    // 查询用户信息表
    async getUserList (baseId) {
      const res = await getUserListApi(baseId)
      // console.log(res)
      this.userList = res.data
    },
    // 字典地块类型
    async getSysSonDictList () {
      const res = await getSysSonDictListApi('DKLX')
      console.log(res.data)
      this.landTypes = res.data
    },
    // 下拉事件 更具userId 匹配对应的phone给到Form.phone
    onSelectChange (value) {
      const userInfo = this.userList.filter((item) => item.userId === value)
      // console.log(userInfo)
      this.Form.phone = userInfo[0].phone
    }

  }
}
</script>

<style lang="scss" scoped>
.addLandPage {
  width: 80.2083vw;
  height: 48.6375vw * 0.834;
  background: #ffffff;
  border-radius: 20px 20px 20px 20px;
  padding-top: 3.6458vw * 0.834;
  position: relative;
  .back {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 24px;
    position: absolute;
    top: 1.5625vw * 0.834;
    left: 1.5625vw * 0.834;
    color: #666666;
    line-height: 0px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    cursor: pointer;
  }
}
//圈地的form
.addMapInForm {
  margin-bottom: 6.25vw * 0.834;
  .text {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #999999;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-top: 1.1458vw * 0.834;
  }
}
.openMapBtn {
  width: 13.0208vw;
  height: 3.125vw * 0.834;
  background: #19b560;
  font-size: 1.0417vw;
  border-radius: 12px 12px 12px 12px;
  // line-height:3.125vw *0.834 ;
}
.addForm {
  width: 750px;
  margin: 0 auto;
}
//所有的input输入框，懒着改了
.landName {
  width: 30.2083vw;
  height: 3.125vw * 0.834;
}
.submitBtn {
  width: 380px;
  height: 60px;
  background: #19b560;
  border-radius: 12px 12px 12px 12px;
  font-size: 20px;
}
::v-deep .el-dialog {
  margin-top: 6vh !important;
}
</style>
